from app import create_app, db
from app.models import Robot, Task
from datetime import datetime, timedelta
import random

# 创建应用
app = create_app()

# 命令行上下文处理器
@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'Robot': Robot, 'Task': Task}

# 初始化测试数据
@app.cli.command("init-test-data")
def init_test_data():
    """初始化测试数据"""
    # 清除现有数据
    db.drop_all()
    db.create_all()
    
    print("正在初始化测试数据...")
    
    # 机器人类型和状态列表
    robot_types = ['cleaning', 'transport', 'inspection', 'delivery']
    robot_statuses = ['online', 'offline', 'maintenance']
    task_statuses = ['pending', 'running', 'completed', 'failed']
    
    # 创建24个测试机器人
    for i in range(24):
        robot_type = random.choice(robot_types)
        status = random.choice(robot_statuses)
        
        # 随机生成最后活动时间
        days_ago = random.randint(0, 30)
        last_active = datetime.utcnow() - timedelta(days=days_ago)
        
        # 生成机器人ID
        robot_id = f'RB-2023-{100 + i:03d}'
        
        # 随机生成网络配置
        ip_address = f'192.168.1.{random.randint(100, 200)}'
        port = random.choice([8080, 8081, 8082, 8083, 80])
        
        # 随机生成硬件参数
        battery_capacity = random.choice([3000, 5000, 8000, 10000])
        max_load = round(random.uniform(1.0, 50.0), 1)
        move_speed = round(random.uniform(0.5, 3.0), 1)
        
        # 创建机器人
        robot = Robot(
            robot_id=robot_id,
            name=f'{get_robot_type_name(robot_type)}-{i+1:02d}',
            type=robot_type,
            description=f'{get_robot_type_name(robot_type)}，用于{get_robot_description(robot_type)}',
            ip_address=ip_address,
            port=port,
            protocol=random.choice(['mqtt', 'http', 'websocket', 'tcp']),
            battery_capacity=battery_capacity,
            max_load=max_load,
            move_speed=move_speed,
            status=status,
            last_active=last_active
        )
        
        db.session.add(robot)
        db.session.flush()  # 获取机器人ID
        
        # 为每个机器人创建1-3个任务
        task_count = random.randint(1, 3)
        for j in range(task_count):
            task_status = random.choice(task_statuses)
            progress = 0
            
            if task_status == 'running':
                progress = random.randint(10, 90)
            elif task_status == 'completed':
                progress = 100
            elif task_status == 'failed':
                progress = random.randint(10, 90)
            
            # 随机生成任务创建时间
            task_days_ago = random.randint(0, days_ago)
            created_at = datetime.utcnow() - timedelta(days=task_days_ago)
            
            task = Task(
                robot_id=robot.id,
                task_name=f'{get_task_name(robot_type, j+1)}',
                progress=progress,
                status=task_status,
                created_at=created_at
            )
            
            db.session.add(task)
    
    # 提交数据
    db.session.commit()
    print(f"测试数据初始化完成！创建了24个机器人和{Task.query.count()}个任务")

def get_robot_type_name(robot_type):
    """获取机器人类型中文名称"""
    type_mapping = {
        'cleaning': '清洁机器人',
        'transport': '搬运机器人',
        'inspection': '巡检机器人',
        'delivery': '配送机器人'
    }
    return type_mapping.get(robot_type, '机器人')

def get_robot_description(robot_type):
    """获取机器人描述"""
    desc_mapping = {
        'cleaning': '室内外清洁工作，自动清扫地面',
        'transport': '货物搬运和运输，支持自动导航',
        'inspection': '设备巡检和安全监控，实时数据采集',
        'delivery': '物品配送和分发，支持多点配送'
    }
    return desc_mapping.get(robot_type, '自动化作业')

def get_task_name(robot_type, task_num):
    """获取任务名称"""
    task_mapping = {
        'cleaning': [
            '大厅区域清洁',
            '走廊通道清扫',
            '会议室深度清洁',
            '卫生间保洁',
            '室外广场清扫'
        ],
        'transport': [
            '仓库货物转运',
            '生产线物料配送',
            '成品仓库入库',
            '原材料运输',
            '跨楼层货物搬运'
        ],
        'inspection': [
            '电力设备巡检',
            '安防监控巡逻',
            '环境数据采集',
            '设备状态检测',
            '安全隐患排查'
        ],
        'delivery': [
            '办公区文件配送',
            '员工餐食分发',
            '物料补给配送',
            '成品出库配送',
            '跨部门物品传递'
        ]
    }
    
    tasks = task_mapping.get(robot_type, ['常规任务'])
    return tasks[task_num % len(tasks)]

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
    